package summer.student.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import summer.student.Dao.ClassDao;
import summer.student.Dao.CourseDao;
import summer.student.Dao.SelectCourseDao;
import summer.student.Dao.StudentDao;
import summer.student.Domain.*;
import summer.student.Utils.Result;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @program: student
 * @description:
 * @author: hlt
 * @create: 2023-07-08 21:16
 * 学生：登录、查询自己的基本信息
 **/
@RestController
@RequestMapping("/students")
@CrossOrigin(origins = "*", maxAge = 3600)  // 后端解决跨域
@Api(tags = "学生管理相关接口")
public class StudentController {

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private SelectCourseDao selectCourseDao;

    @Autowired
    private ClassDao classDao;

    @Autowired
    private CourseDao courseDao;

    @PostMapping("/login")
    public Result stuLogin(@RequestBody Map<String, String> data){
        System.out.println("data: " + data);
        String stuId = data.get("stuId");
        String password = data.get("password");
        if (stuId == null || password == null) return Result.Error("数据不全");
        if (stuId.length() > 20 || password.length() > 20) return Result.Error("数据非法");
        LambdaQueryWrapper<Student> slqw = new LambdaQueryWrapper<>();
        slqw.eq(Student::getStuId, stuId);
        // 学生的姓名是可以重复的！
        Student student = studentDao.selectOne(slqw);
        if(student == null){
            return Result.Error("账号或密码错误");
        }
        if(password.equals(student.getPassword())){
            return Result.Success(stuId);
        }else{
            return Result.Error("账号或密码错误");
        }
    }

    @GetMapping("/selectSelf")
    public Result selectSelf(@RequestParam(name = "stuId", required = true) String stuId){
        LambdaQueryWrapper<Student> slqw = new LambdaQueryWrapper<>();
        slqw.eq(Student::getStuId, stuId);
        Student student = studentDao.selectOne(slqw);
        if(student == null) return Result.ErrorWithSpecialMsg("学生信息未找到！", student);
        else return Result.Success(student);
    }

    @PostMapping("/setClass")
    public Result setClass(@RequestBody Map<String, String>data){
        if (data.get("classId") == null || data.get("stuId") == null)
            return Result.Error("信息不完整或信息有误！");
        long classId = Long.parseLong(data.get("classId"));
        String stuId = data.get("stuId");
        if (stuId.length() > 20) return Result.Error("数据非法");
        // 判断班级和学生是否存在
        Classes aClass = classDao.selectById(classId);
        Student student = studentDao.selectById(stuId);
        // 判断是否重复选课
        LambdaQueryWrapper<SelectCourse> slqw = new LambdaQueryWrapper<>();
        slqw.eq(SelectCourse::getClassId, classId).eq(SelectCourse::getStuId, stuId);
        List<SelectCourse> selectCourses = selectCourseDao.selectList(slqw);
        if (selectCourses.size() != 0) return Result.Error("请勿重复选课！");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SelectCourse selectCourse = new SelectCourse(null, stuId, classId, null, simpleDateFormat.format(date));
        selectCourseDao.insert(selectCourse);
        return Result.Success("选课成功！");
    }

    // 传学生id返回成绩列表
    @GetMapping("/getScoreById")
    public Result getScore(@RequestParam(name="stuId",required = true) String stuId,
                           @RequestParam(name="currentPage", required=false, defaultValue = "1")int currentPage,
                           @RequestParam(name="pageSize", required = false, defaultValue = "10")int pageSize){
        if (stuId.length() > 20) return Result.Error("数据非法");
        LambdaQueryWrapper<SelectCourse> slqw = new LambdaQueryWrapper<>();
        slqw.eq(SelectCourse::getStuId, stuId);

        List<SelectCourse> selectCourses = selectCourseDao.selectList(slqw);
        List<CourseView> courseViews = selectCourses.stream().map(selectCourse -> {
            if (selectCourse.getScore() != null) {
                CourseView courseView = new CourseView();
                Long classId = selectCourse.getClassId();
                Classes classes = classDao.selectById(classId);
                Long courseId = classes.getCourseId();
                Course course = courseDao.selectById(courseId);
                courseView.setCourseId(courseId);
                courseView.setCredit(course.getCredit());
                courseView.setCourseId(classes.getCourseId());
                courseView.setCourseTitle(course.getCourseTitle());
                courseView.setSemester(course.getSemester());
                courseView.setScore(selectCourse.getScore());
                courseView.setCollege(course.getCollege());
                return courseView;
            }
            return null;
        }).collect(Collectors.toList());
        int count = courseViews.size();
        Page<CourseView> courseViewPage = new Page<>(currentPage, pageSize);
        courseViewPage.setRecords(courseViews);
        courseViewPage.setTotal(count);
        courseViewPage.setPages(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        return Result.Success(courseViewPage);
    }

    @PostMapping("/giveUp")  // 学生退课
    public Result giveUp(@RequestBody Map<String, String>data){
        String classId = data.get("classId");
        String stuId = data.get("stuId");
        if (stuId.length() > 20) return Result.Error("数据非法");
        if(classId == null || classId == "" || stuId == "" || stuId == null){
            return Result.Error("数据缺少！");
        }
        System.out.println("classId: " + classId + ", stuId: " + stuId);
        LambdaQueryWrapper<SelectCourse> slqw = new LambdaQueryWrapper<>();
        slqw.eq(SelectCourse::getClassId, classId).eq(SelectCourse::getStuId, stuId);
        SelectCourse selectCourse = null;
        try {
            selectCourse = selectCourseDao.selectOne(slqw);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.Error("数据有误！请停止选课并联系管理员");
        }
        if (selectCourse == null) return Result.Error("选课信息未找到！");
        if(selectCourse.getScore() != null) return Result.Error("老师已经登入成绩，不能退课！");
        else{
            selectCourseDao.delete(slqw);
        }
        return Result.Success("退课成功！");
    }


}